package jpb.Interceptor;

import jpb.constant.StatusCode;
import jpb.module.service.manager.ManagerService;
import jpb.security.HandleCookie;
import jpb.security.HandleToken;
import jpb.util.AnaUrlUtil;
import jpb.util.XmlUtil;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haol on 2017/4/1.
 * 判断操作的组织自己是否为管理员
 */
@Repository
public class ManagerInterceptor extends HandlerInterceptorAdapter {

        private ManagerService managerService;

        public ManagerInterceptor(ManagerService managerService) {
                this.managerService = managerService;
        }

        Logger logger = LoggerFactory.getLogger(ManagerInterceptor.class);
        HandleToken handleToken = new HandleToken();


        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {
                if (XmlUtil.getStrByNode("test").equals("yes")){
                        return true;
                }
               // logger.info("进入管理员拦截器");
                try {
                        String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
                        String mid = handleToken.getValueByKey(token, "id");
                        String url = request.getRequestURI();

                        //logger.info("管理员[{}]访问的路径为{}",mid,url);
                        String oid = AnaUrlUtil.getId("i",url);

                       // logger.info("管理员[{}]访问组织[{}]",mid,oid);
                        boolean pow = managerService.checkManager(mid, oid);
                        if (!pow) {
                                logger.info("用户[{}]没有权限", mid);
                                response.setStatus(Response.SC_FORBIDDEN);
                        }
                        return pow;
                }catch (NullPointerException e) {
                        response.sendRedirect("/index/phoneweb/login/index.html?e=NullPointerException");
                        logger.info("当前用户信息不存在，请重新登录");
                        response.setStatus(Response.SC_UNAUTHORIZED);
                        return false;
                }catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                        return false;
                }
        }
}
